//
//  ArchiveUtils.swift
//  ObjcCodable
//
//  Created by chenbo on 2025/2/10.
//

import Foundation

/// 归档管理器
struct ArchiveUtils {

    /// 文档目录地址
    static var documentsDir: String {
        return NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
    }
    
    /// 删除缓存
    @discardableResult
    static func delete(directoty: String? = nil, fileName: String) -> Bool {
        var path: String!
        if let directoty = directoty {
            path = "\(documentsDir)/\(directoty)/\(fileName).json"
        } else {
            path = "\(documentsDir)/\(fileName).json"
        }
        do {
            try FileManager.default.removeItem(atPath: path)
            return true
        } catch _ {
            return false
        }
    }
    
    /// 删除缓存目录
    @discardableResult
    static func delete(directoty: String) -> Bool {
        let path = "\(documentsDir)/\(directoty)"
        do {
            try FileManager.default.removeItem(atPath: path)
            return true
        } catch _ {
            return false
        }
    }
    
    /// 在文档目录下创建目录
    static func createDirectoryIfNotExistInDocuments(_ directoty: String) {
        let dirPath = "\(documentsDir)/\(directoty)"
        var isExist = ObjCBool.init(true)
        if !FileManager.default.fileExists(atPath: dirPath, isDirectory: &isExist) {
            try? FileManager.default.createDirectory(atPath: dirPath, withIntermediateDirectories: true)
        }
    }
    
    /// 使用Encodable协议进行存储
    @discardableResult
    static func write<T: Encodable>(_ obj: T, toDirectoryName directoty: String? = nil, fileName: String) -> Bool {
        var path: String!
        if let directoty = directoty {
            createDirectoryIfNotExistInDocuments(directoty)
            let dirPath = "\(documentsDir)/\(directoty)"
            path = "\(dirPath)/\(fileName).json"
        } else {
            path = "\(documentsDir)/\(fileName).json"
        }
        guard let data = try? JSONEncoder().encode(obj) else { return false }
        let url = URL(fileURLWithPath: path)
        do {
            try data.write(to: url, options: .atomic)
            return true
        } catch let error {
            print("writting error: \(error)")
            return false
        }
    }
    
    /// 使用Decodable进行读取
    static func read<T: Decodable>(from directoty: String? = nil, fileName: String, aClass: T.Type) -> T? {
        var path: String!
        if let directoty = directoty {
            path = "\(documentsDir)/\(directoty)/\(fileName).json"
        } else {
            path = "\(documentsDir)/\(fileName).json"
        }
        let url = URL(fileURLWithPath: path)
        guard let data = FileManager.default.contents(atPath: url.path) else { return nil}
        let res = try? JSONDecoder().decode(aClass.self, from: data)
        return res
    }
}
